//GameScene Component Constructor
function GameScene() {
	
	//self reference
	var ob = this;
	
	var quicktigame2d = require('com.googlecode.quicktigame2d');
	
	//Create game scene
	this.scene = quicktigame2d.createScene();
	this.scene.color(1, 1, 1);
	
	var rotate_increment = 3;
	
	//create rotating stick
	var Stick = require('ui/Stick');
	var stick;
	
	//create square stand
	var Stand = require('ui/Stand');
	var stand;
	
	this.load = function(){
		stick = new Stick({angle: rotate_increment});
		this.scene.add(stick.getSprite());
		stand = new Stand();
		this.scene.add(stand.getSprite());
	};
	
	//free memory
	this.unload = function(){
		this.scene.remove(stick.getSprite());
		stick = null;
		this.scene.remove(stand.getSprite());
		stand = null;
	};
	
	//function that will do something on click
	this.touch = function(){
		stick.move();
	};
	
	//transform point
	var point = function(x0,y0,x1,y1,x2,y2){
		return ((y0-y1)*(x2-x1)-(x0-x1)*(y2-y1));
	};
	
	//if point is inside triangle
	var triangletest = function(ax,ay,bx,by,cx,cy,px,py){
		//Compute vectors   
		v0x = cx-ax;
		v0y = cy-ay;
		v1x = bx-ax;
		v1y = by-ay;
		v2x = px-ax;
		v2y = py-ay;  
		
		//Compute dot products
		dot00 = v0x*v0x + v0y*v0y;
		dot01 = v0x*v1x + v1y*v0y;
		dot02 = v0x*v2x + v2y*v0y;
		dot11 = v1x*v1x + v1y*v1y;
		dot12 = v1x*v2x + v1y*v2y;
		
		//Compute barycentric coordinates
		invDenom = parseFloat(1 / parseFloat(dot00 * dot11 - dot01 * dot01));
		u = parseFloat(dot11 * dot02 - dot01 * dot12) * invDenom;
		v = parseFloat(dot00 * dot12 - dot01 * dot02) * invDenom;
		
		//Check if point is in triangle
		return ((u >= 0) && (v >= 0) && (u + v < 1));
	};

	var detectCollision = function(){
		//get positions of dimenctions
		var standPos = {};
		standPos.top = stand.getSprite().y;
		standPos.left = stand.getSprite().x;
		standPos.bottom = standPos.top + stand.getSprite().height;
		standPos.right = standPos.left + stand.getSprite().width;

		var stickPos = {};
		stickPos.top = stick.getSprite().y;
		stickPos.left = stick.getSprite().x;
		stickPos.bottom = stickPos.top + stick.size;
		stickPos.right = stickPos.left + stick.size;
		
		//check if stick collides with stand
		if((stickPos.top < standPos.bottom) && (((standPos.left - stick.size) <= stickPos.left) && stickPos.right <= (standPos.right + stick.size)))
		{
			//stick offsets from stick canvas
			var x1 = (stick.size-stick.getSprite().width)/2;
			var y1 = (stick.size-stick.getSprite().height)/2;
	
			//centers and offsets
			var center_x = (stickPos.right - stickPos.left)/2;
			var center_y = (stickPos.bottom - stickPos.top)/2;
			var delta_x = (center_x - x1);
			var delta_y = (center_y - y1);
			center_x = center_x + stickPos.left;
			center_y = center_y + stickPos.top;
	
			//dealing with rotation
			var angle = stick.getAngle();
			if(angle > 180)
			{
				angle -= 180;
			}
			var cosval = Math.cos(-angle + rotate_increment);
			var sinval = Math.sin(-angle + rotate_increment);
	
			var aprx = center_x + Math.round(cosval*delta_x - sinval*delta_y);
			var apry = center_y + Math.round(sinval*delta_x + cosval*delta_y);
	
			var apkx = center_x - Math.round(cosval*delta_x - sinval*delta_y);
			var apky = center_y + Math.round(sinval*delta_x + cosval*delta_y);
	
			var aukx = center_x - Math.round(cosval*delta_x - sinval*delta_y);
			var auky = center_y - Math.round(sinval*delta_x + cosval*delta_y);
	
			var aurx = center_x + Math.round(cosval*delta_x - sinval*delta_y);
			var aury = center_y - Math.round(sinval*delta_x + cosval*delta_y);
			
			//get squares
			var squares = stand.getSprite().tiles;
			var l = squares.length;
			var cols = 10;
			var rows = 10;
			var size = 10;
			var levelCompleted = true;
			for(var i = 0; i < l; i++)
			{
				if(squares[i] > 0)
				{
					//get positions of the square
					var b = new Object();
					b.top = Math.floor(i/cols)*size + standPos.top;
					b.left = i%rows*size + standPos.left;
					b.right = b.left + size;
					b.bottom = b.top + size;
					//check if stick canvas collides with square
					if(((b.bottom + standPos.top)>= stickPos.top) && ((b.left + standPos.left <= stickPos.right) || (b.right + standPos.left >= stickPos.left)))
					{
						var points = [b.left, b.top, b.right, b.top, b.right, b.bottom, b.left, b.bottom];
				
						for(var d = 0; d < points.length-1; d = d + 2)
						{	//check if stick (including rotation) collides with square
							if(triangletest(aukx,auky,apkx,apky,aurx,aury,points[d],points[d+1]) || triangletest(aprx,apry,apkx,apky,aurx,aury,points[d],points[d+1]))
							{
								//if yes decrease tile's image index
								var tile = stand.getSprite().getTile(i);
								tile.gid--;
								squares[i] = tile.gid;
								//save tile data
								stand.getSprite().updateTile(tile);
								break;
							}
						}
					}
					//if still tile haven't reached zero
					if(squares[i] > 0)
					{
						//level is not completed yet
						levelCompleted = false;
					}
				}
			}
			if(levelCompleted)
			{
				//get current level
				var curLevel = Titanium.App.Properties.getInt("currentLevel", 1);
				//increase current level
				curLevel++;
				//save current level
				Titanium.App.Properties.setInt("currentLevel", curLevel);
				//reload level
				ob.unload();
				ob.load();
			}
		}
	};
	
	//function, where we will do steps of our game
	//for example moving object, etc.
	this.step = function(e){
		//no point of detecting collision
		//if stick is not moving
		if(stick.isMoving())
		{
			detectCollision();
		}
		stick.step();
		stand.step();
	};		
}

module.exports = GameScene;
